package com.atguigu.campusintelligentassistantsystem.service;

import com.atguigu.campusintelligentassistantsystem.entity.User;
import com.atguigu.campusintelligentassistantsystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    public User register(User user) {
        // 检查用户名是否已经存在
        Optional<User> existingUser = userRepository.findByUsername(user.getUsername());
        if (existingUser.isPresent()) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 保存用户（密码以明文形式保存，按项目要求）
        return userRepository.save(user);
    }
    
    public User login(String username, String password) {
        Optional<User> user = userRepository.findByUsernameAndPassword(username, password);
        if (user.isEmpty()) {
            throw new RuntimeException("用户名或密码错误");
        }
        return user.get();
    }
    
    public User getUserById(Long id) {
        Optional<User> user = userRepository.findById(id);
        if (user.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }
        return user.get();
    }
    
    public User updateUser(User user) {
        return userRepository.save(user);
    }
    
    /**
     * 更新用户个人信息（手机号、邮箱）
     * @param id 用户ID
     * @param phone 手机号
     * @param email 邮箱
     * @return 更新后的用户
     */
    public User updateUserInfo(Long id, String phone, String email) {
        User user = getUserById(id);
        user.setPhone(phone);
        user.setEmail(email);
        return userRepository.save(user);
    }
    
    /**
     * 重置密码
     * @param id 用户ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 更新后的用户
     */
    public User resetPassword(Long id, String oldPassword, String newPassword) {
        User user = getUserById(id);
        // 验证旧密码是否正确
        if (!user.getPassword().equals(oldPassword)) {
            throw new RuntimeException("旧密码错误");
        }
        user.setPassword(newPassword);
        return userRepository.save(user);
    }
}